﻿/**
 * ...
 * @author 
 */

package bloom.io;

using neko.FileSystem;


class RecursiveDirectoryIterator 

{
	
	private static var isDirectory:String->Bool = function (s:String) return s.isDirectory();
	
	private var baseDir:String;
	private var files:Array<String>;
	private var fileFilter : String->Bool;
    private var dirFilter:String->Bool;
	
	public function new (baseDir:String, fileFilter:String->Bool, ?dirFilter:String->Bool)
	{
		this.baseDir = baseDir;
		
		if (!baseDir.exists()) {
			throw "Base Directory does not exist";
		}
		
        this.dirFilter = dirFilter == null ? FileFilter.noFilter : dirFilter;
        
		this.fileFilter = fileFilter;
		
		files = new Array();
		
		findFiles(baseDir);
	}
	
	private function findFiles(dir:String):Void
	{
		for (f in dir.readDirectory()) 
        {
            var target = dir + "/" + f;
            
			if (target.isDirectory()) 
            {
                if (dirFilter(target)) findFiles(target);
			} 
            else 
            {
				if (fileFilter(target)) files.push(target);
			}
		}
	}
	
	public inline function hasNext ():Bool {
		return files.length > 0;
	}
	
	public inline function next ():String {
		return files.shift();
	}
}